package com.rui.study.algorithm.P_反转链表Ⅱ;

import com.rui.study.algorithm.ListNode;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2019-01-18 08:43
 **/
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        int start = 1;
        int end = 1;

        ListNode p = head;
        ListNode lastNode = null;
        ListNode startPos = null;
        ListNode tmp;
        while (p != null) {
            tmp = p.next;
            if (start >= m) {
                p.next = lastNode;
                lastNode = p;
                if (end == n || tmp == null) {
                    if (startPos == null) {
                        head.next = tmp;
                        head = lastNode;
                    } else {
                        startPos.next.next = tmp;
                        startPos.next = p;
                    }
                    break;
                }
            } else {
                startPos = p;
            }

            p = tmp;

            start++;
            end++;
        }
        return head;
    }




    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;

        System.out.println(print(node1));

        Solution solution = new Solution();
        System.out.println(print(solution.reverseBetween(node1, 2, 5)));

    }

    public static String print(ListNode head) {
        if (head == null) {
            return "";
        }
        String nextVal = print(head.next);
        if (nextVal.length() > 0) {
            nextVal = "->" + nextVal;
        }
        return head.val + nextVal;
    }

}
